const {app, BrowserWindow, Menu, ipcMain} = require('electron')
const path = require('path')
const Store = require('electron-store')

const myStore = new Store({'name': 'InfoStore'})

let mainWindow = null

let username = null

const projectInfo = {
  0: "参与直饮水工程项目, 解决贫困山区饮水问题项目",
  1: "参与百千万残疾儿童家庭健康成长帮扶工程",
  2: "参与乡村教学活动"
}

global.userinfo = {}

function createWindow () {
  //Menu.setApplicationMenu(null)

  mainWindow = new BrowserWindow({
    width: 600,
    height: 650,
    webPreferences: {
      nodeIntegration: true
    }
  })

  mainWindow.loadFile('charityPage/login.html')

  mainWindow.on('closed', function () {
    mainWindow = null
  })
}

let homeWindow = null

ipcMain.on('enter-home-page', (event, message) => {
  if (mainWindow)
    mainWindow.hide()
  if (homeWindow)
    return
  homeWindow = new BrowserWindow({
    height: 960,
    width: 1350,
    webPreferences: {
      nodeIntegration: true
    }
  })
  homeWindow.loadFile('charityPage/home.html')
  username = message
  userinfo.user = message
  homeWindow.on('closed', () => {
    homeWindow = null
    app.quit()
  })
})

ipcMain.on('login-fail', (event, message) => {
  if (mainWindow) {
    mainWindow.loadFile('charityPage/login.html')
  }
})

ipcMain.on('register-fail', (event, message) => {
  if (mainWindow) {
    mainWindow.loadFile('charityPage/register.html')
  }
})

ipcMain.on('get-name', () => {
  if (homeWindow) {
    homeWindow.webContents.send('give-name', username)
  }
})

ipcMain.on('history', (event, history) => {
  let data = {
    time: getNowFormatDate(),
    disc: projectInfo[history],
  }
  let tracks = myStore.get(username)
  if (tracks === undefined) {
    tracks = []
  }
  tracks.push(data)
  myStore.set(username, tracks)
})

ipcMain.on('register-success', () => {
  if (mainWindow) {
    mainWindow.loadFile('charityPage/login.html')
  }
})

ipcMain.on('get-history', () => {
  let tracks = myStore.get(username)
  if (tracks != null && tracks != undefined && tracks.length != 0) {
    homeWindow.webContents.send('send-history', tracks)
  }
})

app.on('ready', createWindow)

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {

  if (mainWindow === null) createWindow()
})

function getNowFormatDate() {
  let date = new Date();
  let seperator1 = "-";
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  let currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}
